package gray.flow;

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;

public class PhotoFlowActivity extends Activity {
    private HorizontalScrollView flow;
	private RelativeLayout root;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        flow=(HorizontalScrollView)findViewById(R.id.flow);
        root=(RelativeLayout)findViewById(R.id.flow_root);
        LayoutInflater inf=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
        for(int i=0;i<30;i++){
        	View rItem=inf.inflate(R.layout.item_layout,null);
        	ImageView iv=(ImageView) rItem.findViewById(R.id.icon_item);
        	LinearLayout.LayoutParams lp=(LayoutParams) iv.getLayoutParams();
        	lp.height=50+new Random().nextInt(50);
        	lp.width=50+new Random().nextInt(50);
        	iv.setLayoutParams(lp);
        	iv.setImageResource(R.drawable.icon);
        	iv.setScaleType(ScaleType.CENTER_CROP);
        	addToRoot(rItem);
        }
        root.postDelayed(new Runnable(){

			@Override
			public void run() {
				root.getWidth();
				
			}
        	
        }, 100);
    }
    private void addToRoot(View v){
    	RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    	if(root.getChildCount()>0){
    		
    		v.setId(100+root.getChildCount());
    		switch(root.getChildCount()%2){
    		case 1:
    			lp.addRule(RelativeLayout.BELOW, root.getChildAt(root.getChildCount()-1).getId());
    			if(root.getChildCount()>1){
    				lp.addRule(RelativeLayout.RIGHT_OF, root.getChildAt(root.getChildCount()-2).getId());
    			}
    			root.addView(v, lp);
    			break;
    		case 0:
    			lp.addRule(RelativeLayout.RIGHT_OF, root.getChildAt(root.getChildCount()-1).getId());
    			if(root.getChildCount()>2){
    				lp.addRule(RelativeLayout.RIGHT_OF, root.getChildAt(root.getChildCount()-2).getId());
    			}
    			
    			root.addView(v, lp);
    			break;
//    		case 3:
//    			//lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//    			lp.addRule(RelativeLayout.ABOVE, root.getChildAt(root.getChildCount()-1).getId());
//    			root.addView(v, lp);
//    			break;
//    		case 0:
//    			lp.addRule(RelativeLayout.RIGHT_OF, root.getChildAt(root.getChildCount()-1).getId());
//    			root.addView(v, lp);
//    			break;
    		}
    	}else{
    		v.setId(100);
    		root.addView(v);
    	}
    }
}